package com.kgc.server.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.kgc.server.service.AlipayService;
import com.kgc.server.util.ResponseMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


@Service
public class AlipayServiceImpl implements AlipayService {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Value("${alipay.appId}")
    private String APP_ID;
    @Value("${alipay.privateKey}")
    private String APP_PRIVATE_KEY;
    @Value("${alipay.zfbPublicKey}")
    private String ALIPAY_PUBLIC_KEY;

    @Override
    public ResponseMessage alipayService(HttpServletRequest req) {
        log.info("AlipayServiceImpl alipayService start...");
        ResponseMessage msg = new ResponseMessage();
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do", APP_ID, APP_PRIVATE_KEY, "json", "utf-8", ALIPAY_PUBLIC_KEY, "RSA2");
        //创建API对应的request类
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", req.getParameter("id"));
        bizContent.put("total_amount", req.getParameter("price"));
        bizContent.put("subject", "测试商品");
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setNotifyUrl("http://2cdc-124-229-125-90.ngrok.io/returnPayMsg");
        request.setReturnUrl("http://localhost:63342/client/BuyCar_Three.html");
        //设置业务参数
//        request.setBizContent("");
        request.setBizContent(bizContent.toString());
        //通过alipayClient调用API，获得对应的response类
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
            log.debug("AlipayServiceImpl alipayService response:" + response);
            if (!response.isSuccess()) {
                msg.setCode("500");
                msg.setMsg("支付错误！");
                return msg;
            }
            msg.setMsg("支付成功！");
            msg.setCode("200");
            msg.setData(response.getBody());
            log.debug("AlipayServiceImpl alipayService  response.getBody:" + response.getBody());

        } catch (Exception e) {
            msg.setCode("500");
            msg.setMsg("报错了请联系管理员！");
            log.error("AlipayServiceImpl alipayService error..", e);
            e.printStackTrace();
        }
        System.out.print(response.getBody());
        //根据response中的结果继续业务逻辑处理
        return msg;
    }

    @Override
    public ResponseMessage returnPayMsg(HttpServletRequest req) {
        log.info("AlipayServiceImpl ResponseMessage req:" + req);
        ResponseMessage msg = new ResponseMessage();
        Map<String, String[]> parameterMap = req.getParameterMap();
        if (parameterMap == null) {
            msg.setCode("500");
            msg.setMsg("错误");
            return msg;
        }
        Map<String, String> map = new HashMap<String, String>();
        Iterator<String> iterator = parameterMap.keySet().iterator();
        for (Iterator<String> iter = iterator; iter.hasNext(); ) {
            String key = iter.next();
            String[] values = parameterMap.get(key);
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < values.length; i++) {
                if (i == values.length - 1) {
                    sb.append(values[i]);
                }else {
                    sb.append(values[i]+",");
                }

            }
            map.put(key,sb.toString());
        }
        map.remove("sing_type");
        try {
            boolean flag = AlipaySignature.rsaCertCheckV2(map, ALIPAY_PUBLIC_KEY, "utf-8", "json");
            if(!flag){
                msg.setCode("500");
                msg.setMsg("失败");
                msg.setData("error");
                return msg;
            }
            if("TRADE_SUCCESS".equals(map.get("trade_status"))||"TRADE_SUCCESS".equals(map.get("TRADE_FINISHED"))){
                msg.setCode("200");
                msg.setData("success");
                msg.setMsg("成功");
            }else {
                msg.setCode("500");
                msg.setMsg("失败");
                msg.setData("error");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg;
    }
}
